package com.lagou.redis;

import org.junit.Test;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public class RedisCluster {


    public static void main(String[] args) {
        JedisCluster jedis;
        // 添加集群的服务节点Set集合
        Set<HostAndPort> hostAndPortsSet = new HashSet<HostAndPort>();
        // 添加节点
        hostAndPortsSet.add(new HostAndPort("192.168.139.121", 7001));
        hostAndPortsSet.add(new HostAndPort("192.168.139.121", 7002));
        hostAndPortsSet.add(new HostAndPort("192.168.139.121", 7003));
        hostAndPortsSet.add(new HostAndPort("192.168.139.121", 7004));
        hostAndPortsSet.add(new HostAndPort("192.168.139.121", 7005));
        hostAndPortsSet.add(new HostAndPort("192.168.139.121", 7006));
        hostAndPortsSet.add(new HostAndPort("192.168.139.121", 7007));
        hostAndPortsSet.add(new HostAndPort("192.168.139.121", 7008));

        // Jedis连接池配置
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // 最大空闲连接数, 默认8个
        jedisPoolConfig.setMaxIdle(10);
        // 最大连接数, 默认8个
        jedisPoolConfig.setMaxTotal(50);
        //最小空闲连接数, 默认0
        jedisPoolConfig.setMinIdle(0);
        // 获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间,  默认-1
        jedisPoolConfig.setMaxWaitMillis(5000); // 设置2秒
        //对拿到的connection进行validateObject校验
        jedisPoolConfig.setTestOnBorrow(true);
        jedis = new JedisCluster(hostAndPortsSet, jedisPoolConfig);

        System.out.println("判断某个键是否存在：" + jedis.exists("username"));
        System.out.println("新增<'username','cym'>的键值对：" + jedis.set("username", "cym"));
        System.out.println("是否存在:" + jedis.exists("username"));

        System.out.println("新增<'password','password'>的键值对：" + jedis.set("password", "123456"));
        System.out.println("删除键password:" + jedis.del("password"));
        System.out.println("判断键password是否存在：" + jedis.exists("password"));
        System.out.println("设置键username的过期时间为10s:" + jedis.expire("username", 10));
        // TimeUnit.SECONDS.sleep(2); // 线程睡眠2秒
        System.out.println("查看键username的剩余生存时间：" + jedis.ttl("username"));
        System.out.println("查看键username的剩余生存时间：" + jedis.ttl("username"));
        System.out.println("移除键username的生存时间：" + jedis.persist("username"));
        System.out.println("查看键username的剩余生存时间：" + jedis.ttl("username"));
        System.out.println("查看键username所存储的值的类型：" + jedis.type("username"));
    }

}
